//package com.weimob.mcloud.wechatwork.customer.job;
//
//import com.alibaba.dubbo.config.annotation.Reference;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.google.common.collect.Lists;
//import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.request.SelfExternalContactGetDTO;
//import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.ExternalContactBO;
//import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.FollowUserBO;
//import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.SelfExternalContactGetBO;
//import com.weimob.mcloud.wechatwork.core.adapter.service.ChannelAdapterService;
//import com.weimob.mcloud.wechatwork.core.base.CommonParam;
//import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
//import com.weimob.mcloud.wechatwork.core.base.SingleRequest;
//import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
//import com.weimob.mcloud.wechatwork.core.entity.relation.CustomerEmployeeRelation;
//import com.weimob.mcloud.wechatwork.core.entity.relation.customer.Customer;
//import com.weimob.mcloud.wechatwork.core.entity.relation.employee.Employee;
//import com.weimob.mcloud.wechatwork.core.enums.customer.CustomerStatusEnum;
//import com.weimob.mcloud.wechatwork.core.enums.customer.ExternalUserAddWayEnum;
//import com.weimob.mcloud.wechatwork.core.enums.customer.ExternalUserTypeEnum;
//import com.weimob.mcloud.wechatwork.core.enums.customer.GenderEnum;
//import com.weimob.mcloud.wechatwork.core.service.customer.CustomerService;
//import com.weimob.mcloud.wechatwork.core.service.customer.request.CustomerByIdsRequest;
//import com.weimob.mcloud.wechatwork.core.service.employee.EmployeeService;
//import com.weimob.mcloud.wechatwork.core.service.employee.request.SingleEmployeeAttachRequest;
//import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
//import com.weimob.mcloud.wechatwork.customer.domain.ArtemisBaseInfo;
//import com.weimob.mcloud.wechatwork.customer.domain.ArtemisConstant;
//import com.weimob.mcloud.wechatwork.customer.domain.ExternalUserChangeInfo;
//import com.weimob.mcloud.wechatwork.customer.mq.dto.AddExternalUserSecondDTO;
//import com.weimob.mcloud.wechatwork.customer.service.TagManageService;
//import com.weimob.mcloud.wechatwork.customer.service.user.enums.CustomerLoseTypeEnum;
//import com.weimob.mcloud.wechatwork.customer.service.user.enums.YesOrNoEnum;
//import com.weimob.soa.common.response.SoaResponse;
//import com.weimob.soa.common.utils.SoaUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.collections.CollectionUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
///**
// * @author junlong.lv
// * @version 1.0
// * @date 2022/7/8 11:13 上午
// */
//@Slf4j
//@Service
//public class RepairCustomerDataJob {
//
//    @Reference
//    private CustomerService customerService;
//
//    @Autowired
//    private ChannelAdapterService channelAdapterService;
//
//    @Reference
//    private EmployeeService employeeService;
//
//    @Autowired
//    private TagManageService tagManageService;
//
//    @Reference
//    private PrivateSphereService privateSphereService;
//
//    /**
//     * 企微助手产品id
//     */
//    @Value("${aewc.productId:203}")
//    private Long aewcProductId;
//
//    public void repairCustomerData(String corpId, String externalUserId) {
//
//        PrivateSphere privateSphereRequest = new PrivateSphere();
//        privateSphereRequest.setCorpId(corpId);
//        privateSphereRequest.setProductId(aewcProductId);
//        SoaResponse<PrivateSphere, Void> fetchPrivateSphere = privateSphereService.fetch(privateSphereRequest);
//        if (0L != Long.parseLong(fetchPrivateSphere.getReturnCode()) || Objects.isNull(fetchPrivateSphere.getResponseVo())) {
//            //1.1、私域不存在，返回（不落非企微产品外部联系人数据）
//            log.info("消费新增外部联系人消息查询私域信息失败:{}", JSON.toJSONString(privateSphereRequest));
//            return;
//        }
//
//        PrivateSphere privateSphere = fetchPrivateSphere.getResponseVo();
//
//        //3、查询企微客户详情,根据corpId和externalUserId查询
//        SelfExternalContactGetDTO selfExternalContactGetDTO = new SelfExternalContactGetDTO();
//        selfExternalContactGetDTO.setCorpId(corpId);
//        selfExternalContactGetDTO.setExternalUserId(externalUserId);
//        //log.info("新中台消费消息从企微获取外部联系人：request {}", JSON.toJSONString(selfExternalContactGetDTO));
//        SoaResponse<SelfExternalContactGetBO, Void> selfExternalContactSoaResponse = channelAdapterService
//                .getSelfExternalContact(selfExternalContactGetDTO);
//        log.info("修复客户数据, 根据externalUserId查询官方客户数据, request:{}, response {}", JSON.toJSONString(selfExternalContactGetDTO),
//                JSON.toJSONString(selfExternalContactSoaResponse));
//
//        if (Objects.isNull(selfExternalContactSoaResponse)
//                || 0L != Long.parseLong(selfExternalContactSoaResponse.getReturnCode())
//                || Objects.isNull(selfExternalContactSoaResponse.getResponseVo())) {
//            log.error("修复客户数据, 查询官方客户数据失败 request:{}, response:{}",
//                    JSON.toJSONString(selfExternalContactGetDTO), JSON.toJSONString(selfExternalContactSoaResponse));
//            //3.1 企微客户不存在，打印日志直接返回
//            return;
//        }
//
//
//        SelfExternalContactGetBO selfExternalContactGetBO = selfExternalContactSoaResponse.getResponseVo();
//
//
//
//
//
//        log.info("处理新增外部联系人消息：response {}", JSON.toJSONString(selfExternalContactGetBO));
//        ExternalContactBO externalContactBO = selfExternalContactGetBO.getExternalContactBO();
//        List<FollowUserBO> followUserList = selfExternalContactGetBO.getFollowUser();
//        String phone = this.getExternalUserPhone(followUserList);
//
//
//
//        //5、查询本地企微用户信息（没有需要写入）
//        CustomerByIdsRequest customerByIdsRequest = new CustomerByIdsRequest();
//        customerByIdsRequest.setExternalUserids(Lists.newArrayList(externalUserId));
//        Customer customerByIds = new Customer();
//        customerByIds.setCorpId(corpId);
//        customerByIdsRequest.setCustomer(customerByIds);
//
//        List<Customer> customerResponseList =
//                SoaUtil.unpack(customerService.fetchCustomerByIds(customerByIdsRequest, new CommonParam()));
//
//        Boolean newUserFlag = false;
//        Customer customer = new Customer();
//        customer.setCorpId(corpId);
//        customer.setExternalUserid(externalUserId);
//        customer.setName(externalContactBO.getName());
//        customer.setAvatar(externalContactBO.getAvatar());
//        customer.setGender(GenderEnum.getEnumByValue(externalContactBO.getGender()));
//        customer.setPosition(externalContactBO.getPosition());
//        customer.setCorpName(externalContactBO.getCorpName());
//        customer.setCorpFullName(externalContactBO.getCorpFullName());
//        customer.setExternalUserType(ExternalUserTypeEnum.getEnumByValue(externalContactBO.getType()));
//        customer.setUnionid(externalContactBO.getUnionid());
//        if (phone != null) {
//            customer.setPhone(phone);
//            customer.setMobiles(phone);
//        }
//        customer.setStatus(CustomerStatusEnum.DEFAULT);
//        if(customerResponseList == null || customerResponseList.size() == 0){
//            //5.1 如果本地不存在，新增外部联系人数据
//            log.info("新中台外部联系人新增客户：request {}", JSON.toJSONString(customer));
//            customer = SoaUtil.unpack(customerService.createCustomer(customer));
//            log.info("新中台外部联系人新增客户：response {}", JSON.toJSONString(customer));
//            newUserFlag = true;
//        }else{
//            //5.2 如果本地数据存在，更新外部联系人最新数据
//            customer.setId(customerResponseList.get(0).getId());
//            log.info("新中台外部联系人更新客户：request {}", JSON.toJSONString(customer));
//            customer = SoaUtil.unpack(customerService.updateCustomer(customer));
//            log.info("新中台外部联系人更新客户：response {}", JSON.toJSONString(customer));
//            if (phone != null) {
//                log.info("新中台外部联系人客户详情表更新手机号：request {}", JSON.toJSONString(customer));
//                SoaUtil.unpack(customerService.updateCustomerDeatil(customer));
//                log.info("新中台外部联系人客户详情表更新手机号：request {}", JSON.toJSONString(customer));
//            }
//        }
//
//        //6、查询客户员工关系数据（如果不存在需要写入，存在需要更新）查询该客户所有关联员工是为了给二阶段业务处理使用
//        Boolean userStateChangeFlag = false;
//        CustomerEmployeeRelation customerEmployeeRelation = new CustomerEmployeeRelation();
//        customerEmployeeRelation.setCorpId(corpId);
//        customerEmployeeRelation.setCustomerId(customer.getId());
//        SingleRequest<CustomerEmployeeRelation> request = new SingleRequest<>(customerEmployeeRelation);
//        MultiResponse<CustomerEmployeeRelation> customerEmpRelResponsePageInfoResponse =
//                SoaUtil.unpack(customerService.fetchCustomerEmployeeRelation(request));
//
//
//        //key: orgUserId， value：客户员工关系数据对象
//        Map<String, CustomerEmployeeRelation> customerEmployeeRelationMap = new LinkedHashMap<>();
//        if(customerEmpRelResponsePageInfoResponse != null
//                && customerEmpRelResponsePageInfoResponse.getDataList() != null){
//            for (CustomerEmployeeRelation employeeRelation : customerEmpRelResponsePageInfoResponse.getDataList()) {
//                customerEmployeeRelationMap.put(employeeRelation.getEmployee().getId(), employeeRelation);
//            }
//        }
//
//        for (FollowUserBO followUserBO : followUserList) {
//
//
//            //2、查询员工, 判断员工是否存在
//            Employee employee = new Employee();
//            employee.setCorpId(corpId);
//            SingleEmployeeAttachRequest<Employee> attachRequest = new SingleEmployeeAttachRequest<>();
//            attachRequest.setTxUserId(Lists.newArrayList(followUserBO.getUserid()));
//            attachRequest.setData(employee);
//            List<Employee> employeeResDTOList =
//                    SoaUtil.unpack(employeeService.fetchEmployee(attachRequest)).getDataList();
//            if (CollectionUtils.isEmpty(employeeResDTOList)) {
//                //2.1、员工不存在，需要打日志具体排查
//                log.error("修复客户数据, 查询员工未查到, txUserId:{}", JSON.toJSONString(followUserBO.getUserid()));
//                continue;
//            }
//
//            //6.1 遍历客户所属员工
//            //6.1.1 处理消息体的员工数据
//            Employee employeeResDTO = employeeResDTOList.get(0);
//            String employeeId = employeeResDTO.getId();
//            customerEmployeeRelation.setEmployee(employeeResDTO);
//
//
//            Date followUserCreateTime = new Date(followUserBO.getCreatetime()*1000L);
//            customerEmployeeRelation.setAddTime(followUserCreateTime);
//            customerEmployeeRelation.setAddWay(ExternalUserAddWayEnum.getEnumBycode(followUserBO.getAddWay()));
//            customerEmployeeRelation.setRemark(followUserBO.getRemark());
//            customerEmployeeRelation.setRemarkCorpName(followUserBO.getRemarkCorpName());
//            customerEmployeeRelation.setDescription(followUserBO.getDescription());
//            customerEmployeeRelation.setState(followUserBO.getState());
//            customerEmployeeRelation.setBizEventAddTime(followUserCreateTime);
//            customerEmployeeRelation.setStatus(CustomerStatusEnum.DEFAULT);
//
//            CustomerEmployeeRelation customerEmployeeRelationResult = customerEmployeeRelationMap.get(employeeId);
//            if(customerEmployeeRelationResult == null){
//                //6.1.1 本地不存在该员工客户关系，新增数据
//                log.info("新中台消费外部联系人新增客户员工关系：requeset {}", JSON.toJSONString(customerEmployeeRelation));
//                customerEmployeeRelation.setFriended(true);
//                CustomerEmployeeRelation unpack = SoaUtil.unpack(customerService.createCustomerEmployeeRelation(customerEmployeeRelation));
//                userStateChangeFlag = true;
//                log.info("新中台消费外部联系人新增客户员工关系：response {}", JSON.toJSONString(unpack));
//            }else{
//                //6.1.2 本地存在客户员工关系，更新数据
//                if (!customerEmployeeRelationResult.getFriended() &&
//                        followUserCreateTime.before(customerEmployeeRelationResult.getLoseTime())) {
//                    //6.1.3 非好友变成好友状态，并且企微成为好友时间小于本地流失时间
//                    //（户删除员工再加回来 腾讯成为好友时间不变，流失时间是微盟侧定义的，流失时间就会大于腾讯成为好友时间）
//                    // 需要初始化自己业务的一个添加好友时间提供BI使用
//                    customerEmployeeRelation.setBizEventAddTime(new Date());
//                }
//
//                //6.1.4 历史同步事件
//                if (CustomerLoseTypeEnum.EMPLOYEE_DEL_CUSTOMER.getCode().equals(customerEmployeeRelationResult.getLoseType())) {
//                    //6.1.5 单向删除员工删除客户，需要将流失类型置为初识标识
//                    customerEmployeeRelation.setLoseType(CustomerLoseTypeEnum.INIT.getCode());
//                    customerEmployeeRelation.setFriended(Boolean.TRUE);
//                }
//
//                String localState = customerEmployeeRelationResult.getState();
//                Date localAddTime = customerEmployeeRelationResult.getAddTime();
//                String txState = followUserBO.getState();
//                //数据同步状态本地和企微state不一致需要通知裂变活动
//                if(!Objects.equals(localState, txState)){
//                    userStateChangeFlag = true;
//                }
//                //数据同步状态本地和企微添加好友时间不一致需要通知裂变活动
//                if(followUserCreateTime.compareTo(localAddTime) !=0){
//                    userStateChangeFlag = true;
//                }
//
//                //6.1.6 更新员工客户关系数据
//                log.info("新中台消费外部联系人更新客户员工关系：requeset {}", JSON.toJSONString(customerEmployeeRelation));
//                CustomerEmployeeRelation unpack = SoaUtil.unpack(customerService.updateCustomerEmployeeRelation(customerEmployeeRelation));
//                log.info("新中台消费外部联系人更新客户员工关系：response{}", JSON.toJSONString(unpack));
//            }
//
//            try {
//                //
//                log.info("添加外部联系人, 新增初始化外部联系人标签, privateSphere:{}, externalUserId:{}, " +
//                        "followUserBO:{}", JSON.toJSONString(privateSphere), externalUserId, JSON.toJSONString(followUserBO));
//                //6.1.7 初始化客户标签
//                tagManageService.initCustomerTag(privateSphere, externalUserId, followUserBO);
//            } catch (Exception e) {
//                log.error("新增客户, 添加客户标签失败, corpId:{}, externalUserId:{}, error:{}",
//                        corpId, externalUserId, JSON.toJSONString(e));
//            }
//
//            //6.1.8 发消息进行二阶段的操作(注意消息体不能过大，过滤无效字段数据)
//            AddExternalUserSecondDTO addExternalUserSecondDTO = new AddExternalUserSecondDTO();
//            addExternalUserSecondDTO.setCustomerId(customer.getId());
//            addExternalUserSecondDTO.setNewUserFlag(newUserFlag);
//            addExternalUserSecondDTO.setRemarkMobiles(followUserBO.getRemarkMobiles());
//            addExternalUserSecondDTO.setCurrentRelation(filterInvalidRelationAtt(customerEmployeeRelation));
//            addExternalUserSecondDTO.setUserStateChangeFlag(userStateChangeFlag);
//            if(customerEmployeeRelationMap.values().size() > 0){
//                List<CustomerEmployeeRelation> results = Lists.newArrayList();
//                for (CustomerEmployeeRelation value : customerEmployeeRelationMap.values()) {
//                    CustomerEmployeeRelation filterResult = filterInvalidRelationAtt(value);
//                    results.add(filterResult);
//                }
//                addExternalUserSecondDTO.setHisRelationList(results);
//            }
//
//
////            ExternalUserChangeInfo externalUserChangeInfo = new ExternalUserChangeInfo();
////            addExternalUserSecondDTO.setExternalUserChangeInfo(externalUserChageInfo);
////            ArtemisBaseInfo<AddExternalUserSecondDTO> artemisBaseInfo = new ArtemisBaseInfo();
////            if(YesOrNoEnum.YES.getCode().equals(externalUserChageInfo.getHistoryCustomerSync())){
////                //历史消息
////                artemisBaseInfo.setTopic(ArtemisConstant.Topic.HISTORY_CORP_EXTERNALUSER_SECOND_EVENT);
////            }else{
////                //实时消息
////                artemisBaseInfo.setTopic(ArtemisConstant.Topic.CORP_EXTERNALUSER_SECOND_EVENT);
////            }
////
////            artemisBaseInfo.setEvent(addExternalUserSecondDTO);
////            artemisBaseInfo.setProducer(ArtemisConstant.USER);
////            artemisService.sendToArtemis(artemisBaseInfo);
//            break;
//        }
//
//
//    }
//
//    /**
//     * 获取外部联系人手机号信息【仅通过搜索手机号添加方式获取】
//     *
//     * @param followUser
//     */
//    public String getExternalUserPhone(List<FollowUserBO> followUser) {
//        if (CollectionUtils.isEmpty(followUser)) {
//            return null;
//        }
//        log.info("followUser={}", JSONObject.toJSONString(followUser));
//        List<FollowUserBO> followUserList = followUser.stream().filter(item ->
//                ExternalUserAddWayEnum.PHONE_SEARCH.getCode().equals(item.getAddWay())
//        ).collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(followUserList)) {
//            //没有通过手机号搜索添加的 不处理
//            return null;
//        }
//        log.info("followUserList={}", JSONObject.toJSONString(followUserList));
//        //只获取第一个手机号
//
//        List<String> remarkMobiles = Lists.newArrayList();
//        followUserList.forEach(e -> {
//            if (CollectionUtils.isNotEmpty(e.getRemarkMobiles())) {
//                remarkMobiles.addAll(e.getRemarkMobiles());
//            }
//        });
//        log.info("remarkMobiles={}", JSONObject.toJSONString(remarkMobiles));
//        return CollectionUtils.isEmpty(remarkMobiles) ? null : remarkMobiles.get(0);
//    }
//
//    /**
//     * 客户员工关系转换去除无效数据
//     * @param customerEmployeeRelation
//     * @return
//     */
//    private CustomerEmployeeRelation filterInvalidRelationAtt(CustomerEmployeeRelation customerEmployeeRelation) {
//        CustomerEmployeeRelation customerEmployeeRelationResult = new CustomerEmployeeRelation();
//        Employee employeeInfo = customerEmployeeRelation.getEmployee();
//        if(employeeInfo != null){
//            Employee employeeResult = new Employee();
//            employeeResult.setId(employeeInfo.getId());
//            employeeResult.setName(employeeInfo.getName());
//            employeeResult.setTxUserId(employeeInfo.getTxUserId());
//            employeeResult.setActionLogs(null);
//            employeeResult.setCustomers(null);
//            employeeResult.setDepartments(null);
//            employeeResult.setExtInfo(null);
//            employeeResult.setTagDetails(null);
//            employeeResult.setGroups(null);
//            customerEmployeeRelationResult.setEmployee(employeeResult);
//        }
//        customerEmployeeRelationResult.setAddTime(customerEmployeeRelation.getAddTime());
//        customerEmployeeRelationResult.setState(customerEmployeeRelation.getState());
//        customerEmployeeRelationResult.setFriended(customerEmployeeRelation.getFriended());
//        customerEmployeeRelationResult.setAddWay(customerEmployeeRelation.getAddWay());
//        customerEmployeeRelationResult.setExtInfo(null);
//        return customerEmployeeRelationResult;
//    }
//
//
//}
